const config = require('../config')

const errorHandler = (err, req, res, next) => {
  let error = { ...err }
  error.message = err.message

  // 记录错误日志
  console.error('API错误:', {
    message: err.message,
    stack: err.stack,
    url: req.originalUrl,
    method: req.method,
    ip: req.ip,
    userAgent: req.get('User-Agent')
  })

  // MySQL错误处理
  if (err.code === 'ER_DUP_ENTRY') {
    const message = '数据已存在，请勿重复操作'
    error = { message, statusCode: 400, code: 'DUPLICATE_ENTRY' }
  }

  if (err.code === 'ER_NO_REFERENCED_ROW_2') {
    const message = '关联数据不存在'
    error = { message, statusCode: 400, code: 'FOREIGN_KEY_CONSTRAINT' }
  }

  // JWT错误处理
  if (err.name === 'JsonWebTokenError') {
    const message = '无效的访问令牌'
    error = { message, statusCode: 401, code: 'INVALID_TOKEN' }
  }

  if (err.name === 'TokenExpiredError') {
    const message = '访问令牌已过期'
    error = { message, statusCode: 401, code: 'TOKEN_EXPIRED' }
  }

  // 验证错误处理
  if (err.name === 'ValidationError') {
    const message = Object.values(err.errors)
      .map(val => val.message)
      .join(', ')
    error = { message, statusCode: 400, code: 'VALIDATION_ERROR' }
  }

  // 文件上传错误
  if (err.code === 'LIMIT_FILE_SIZE') {
    const message = '文件大小超出限制'
    error = { message, statusCode: 400, code: 'FILE_TOO_LARGE' }
  }

  // 权限错误
  if (err.name === 'UnauthorizedError') {
    const message = '访问被拒绝，请先登录'
    error = { message, statusCode: 401, code: 'UNAUTHORIZED' }
  }

  // 默认错误响应
  const statusCode = error.statusCode || 500
  const message = error.message || '服务器内部错误'
  const code = error.code || 'INTERNAL_SERVER_ERROR'

  res.status(statusCode).json({
    success: false,
    message,
    code,
    ...(config.server.env === 'development' && {
      stack: err.stack,
      error: err
    })
  })
}

module.exports = errorHandler
